<template>
    <div>
        <swiper 
            class="swiper" 
            @change="swiperChange" 
            :current="current" 
            :vertical="true"
            :indicator-dots="false" :autoplay="false" :interval="3000" :duration="300">
            <swiper-item v-for="(item, index) in videoList" :key="index" class="video_container">
                <video object-fit="contain"
                    v-if="(current === index || current + 1 == index || current - 1 == index) && item.context" 
                    :id="`video_${index}`"
                    :poster="item.pictureUrl || ''"
                    :src="item.context"
                    @play="videoStatus($event, 'onplay')"
                    @pause="videoStatus($event, 'onpause')"
                    @ended="videoStatus($event, 'onended')"
                    @timeupdate="videoTimeupdate"
                    :controls="false"></video>
                <div v-if="(current === index || current + 1 == index || current - 1 == index)" class="video_cover" :style="{background: isPause ? 'rgba(0,0,0,0.5)' : 'transparent'}" @click.self="videoPlayOrPause">
                    <!-- <span class="video_num"> {{current}}/{{videoList.length}} </span> -->
                    <div v-if="isPause" class="play_icon">
                        <i class="icon-video-play" @click.self="videoPlayOrPause" ></i>
                        <span>{{videoTime.fomatCurrentTime}} / {{videoTime.formatDuration}}</span>
                    </div>

                    <div @click="backTop" class="back_material w150 h60 fs26 color-fff flex-center">
                        <i class="fs20 mar-r10 icon-arrow-left"></i>
                        素材库
                        <!-- {{current}}/{{videoList.length}} -->
                    </div>   
                    <div v-if="canEdit" @click="changeTitle(item)" class="change_title h60 fs26 pad-lr20 flex-center color-fff">
                        <i class="icon-edit mar-r10"></i>
                        改标题
                    </div>
                    <div v-if="$store.getters.isSuperManger" @click="deleteVideo(item, index)" class="delete_video h60 fs26 pad-lr20 flex-center color-fff">
                        <i class="icon-delete3 mar-r5"></i>
                        删除视频
                    </div>
                    <div v-if="shareKey" @click="changeMyCard" style="background: @mainColor" class="change_title h60 fs26 pad-lr20 flex-center color-fff">
                        换成我的
                    </div>

                    <div class="right_icon flex-column flex-v-center">
                        <div class="icon_item avator">
                            <image :src="cardInfo.headImg" mode="" />
                        </div>
                        <!-- <template v-else>
                            <div v-if="canEdit" @click="showMyCard"  class="icon_item flex-center flex-column avator">
                                <em class="fs20 icon-plus"></em>
                                <span class="fs22" style="color: #333">头像</span>
                            </div>
                        </template> -->
                        <div class="icon_item" @click="toPraise(item)">
                            <i v-if="item.praiseFlag" style="color: red" class="icon-dianzan_kuai"></i>
                            <i v-else class="icon-dianzan"></i>
                            <p>{{item.praiseCnt}}</p>
                        </div>
                        <div class="icon_item" @click="shareCopy(item)">
                            <i class="icon-pengyouquan"></i>
                            <p>配文</p>
                        </div>
                        <div class="icon_item" @click="createPoster">
                            <i class="icon-tupian"></i>
                            <p>海报</p>
                        </div>
                    </div>

                    <div class="download" @click="saveToPhone(item)">
                        <i class="icon-xiazai"></i>
                        <p> 保存到相册 </p>
                    </div>

                    <!-- <div class="download" v-if="hasAlreadyWxConfig">
                        <wx-open-launch-weapp class="wx-open-launch-weapp" id="launch-btn" username="gh_3ee79c3351ae" path="/pages/index/index.html">
                            <script type="text/wxtag-template">
                                <img style="width:100%" src="" alt="">
                            </script>
                        </wx-open-launch-weapp>
                    </div> -->

                    <div class="ad_container">
                        <template v-if="advertInfo.id || defaultAdverInfo.id">
                            <div v-if="advertInfo.id" class="v_ad_info">
                                <adItem :shareKey="shareKey" :item="advertInfo" style="padding:0;"></adItem>
                            </div>
                            <div v-else-if="defaultAdverInfo.id" class="v_ad_info">
                                <adItem :shareKey="shareKey" :item="defaultAdverInfo" style="padding:0;"></adItem>
                            </div>
                            <div v-if="canEdit" class="ad_btn" @click="insertAd">
                                ↑ 更换广告 ↑
                            </div>
                            <div v-else class="ad_btn" @click="changeMyCard">
                                ↑ 换成我的广告 ↑
                            </div>
                        </template>

                        <template v-else>
                            <p v-if="canEdit" @click="insertAd" class="v_ad_info flex-center">
                                <i class="icon-plus fs22 mar-r10"></i>
                                添加我的广告
                            </p>
                            <div v-else class="ad_btn" @click="changeMyCard">
                                添加我的广告
                            </div>
                        </template>
                        <!-- <div class="ad_info"></div> -->
                        
                    </div>
                </div>
            </swiper-item>
        </swiper>

        <uni-popup ref="downloadVide" type="center">
            <div class="alert_download_video">
                <div class="title">下载视频</div>
                <div class="img_con">
                    <image :src="downloadCodeUrl" @error="handleDownloadCodeUrlError" mode="widthFix"></image>
                    <div class="error" v-if="downloadCodeError">
                        <span> 图片错误 </span>
                        <span @click="copyErrorUrl"> {{downloadCodeUrl}} </span>
                    </div>
                </div>
                <p>长按识别小程序码，前往领取</p>
            </div>
        </uni-popup>

        <adSelecter ref="adSelecter" type="视频" adPosPick></adSelecter>
        <pub-timeline-tip ref="timelineTip"></pub-timeline-tip>
        <pub-text-editer ref="textEditer"></pub-text-editer>
        <createPoster ref="createPoster"></createPoster>
        <gzhPopup ref="gzhPopup"></gzhPopup>
        <setDynamic ref="setDynamic"></setDynamic>
        
    </div>
</template>

<script>
import { getDynamicVideoList, getDynamicInfo, praiseDynamic, shareDynamic, getUserShareInfo, updateShareTemp, userHisLeave   } from '@/request/art'
import { getUserAdverts ,clickAdvert } from '@/request/ad'
import { getAppCode } from '@/request/base'
import adItem from '@/components/pages/adItem'
import adSelecter from '@/components/pages/adSelecter'
import createPoster from '@/components/pages/createPoster'
import gzhPopup from '@/components/pages/gzh-popup'
import { sysDeleArt } from '@/request/sys'
import setDynamic from '@/components/pages/setDynamic'
import qs from 'qs'
import { timestampToLocalDayPlus, timestampToCountdown, throttle } from '@/utils/functions'
import { listerPageClose, navSendBeacon } from '@/utils/pageClose'

export default {
    components: {
        createPoster,
        adSelecter,
        adItem,
        gzhPopup,
        setDynamic
    },
    data() {
        return {
            current: 0,
            videoContext: null,
            isPause: false,
            videoTime: {
                maxCurrentTime: '',
                currentTime: '',
                duration: '',
                fomatCurrentTime: '',
                formatDuration: '',
            },
            videoList: [],
            scroll: {
                page: 1,
                size: 10,
                max: false,
                loading: false,
            },

            dynamicId: '', //视频id

            shareKey: '', //分享key
            fromUserId: '', //shareKey对应的UserId
            tempShareKey: (new Date().getTime().toString(32)) + (Math.random().toString(32).slice(2)), //前端生成的分享id,要传给后台的

            defaultAdverInfo: {},
            advertInfo: {},
            shareCardInfo: null,
            hasAlreadyWxConfig: false,
            downloadCodeUrl: '',
            downloadCodeError: false,

        }
    },
    computed: {
        detail() {
            return this.videoList[this.current]
        },
        canEdit() {
            return !this.shareKey
        },
        showCard() {
            return this.$store.state.user.userInfo.dynamicShowCard == '01'
        },
        cardInfo() {
            if(this.shareKey) {
                return this.shareCardInfo || {}
            } else {
                return this.$store.state.user.userInfo || {}
            }
        }
    },
    async onLoad(options) {
        this.dynamicId = options.id
        if(options.shareKey) this.shareKey = options.shareKey;
        await this.getDetail()
        this.wxConfig()

        if(options.isPoster) {
            if(this.mixinLoginStatus) {
                // 沒登錄沒必要更新瀏覽狀態
                await updateShareTemp({ frontKey: this.shareKey })
            }
        }
        if(options.shareKey) {
            this.getShareInfo()
        } else {
            this.getVideoList()
            this.getDefaultAd()
        }

        // 监听浏览器关闭事件
        listerPageClose(() => {
            navSendBeacon({
                token: this.$store.state.user.account.token,
                hisId: this.detail.hisId, 
                second: Math.floor(this.videoTime.currentTime),
                timeStr: Math.floor(this.videoTime.duration)
            })
        })
    },
    onUnload() {
        this.uploadReadTime()
    },
    onHide() {
        this.uploadReadTime()
    },
    methods: {
        getShareInfo() {
            getUserShareInfo({
                frontKey: this.shareKey,
            }).then(res => {
                uni.setStorageSync( 'shareUserId', res.data.fromUserId)
                this.fromUserId = res.data.fromUserId
                if(res.data.hasOwnProperty('advert')) {
                    let advertInfo = res.data.advert || {}
                    this.advertInfo = advertInfo
                }

                if(res.data.hasOwnProperty('headImg')) {
                    this.shareCardInfo = res.data
                } else {
                    this.shareCardInfo = null
                }
            })
        },
        getDefaultAd() {
            getUserAdverts({
                defalutFlag: '01',
                pageIndex: 1,
                pageSize: 1
            }).then(async res => {
                let advertInfo = res.data.list[0]
                this.defaultAdverInfo = advertInfo || {}
            })
        },
        getDetail() {
            return new Promise(async (resolve, reject) => {
                getDynamicInfo({
                    frontKey: this.shareKey || void 0,
                    dynamicId: this.dynamicId
                }).then(res => {
                    document.title = res.data.dynamic.title
                    let detail = res.data.dynamic
                    this.videoList.push({
                        ...detail,
                        praiseFlag: res.data.hasPraise,
                        hisId: res.data.hisId
                    })
                    this.initVideoContext()
                    // this.videoContext = uni.createVideoContext('video_' + this.current, this)
                    // this.videoContext.play()                    

                    console.log(detail.userId);
                    if(detail.userId == this.$store.state.user.userInfo.userId && (!detail.industryNames || detail.industryNames.length == 0)) {
                        this.$refs.setDynamic.open({dynamicId: detail.id})
                    }
                    resolve()         
                })
            })
        },
        getVideoList() {
            if(this.scroll.loading || this.scroll.max) return;
            this.scroll.loading = true;
            getDynamicVideoList({
                noIdStrs: this.dynamicId,
                pageIndex: this.scroll.page,
                pageSize: this.scroll.size
            }, { complete: () => {
                this.scroll.loading = false;
            }}).then(res => {
                this.videoList = this.videoList.concat(res.data.list)
                this.scroll.page = res.data.nextPage
                this.scroll.max = res.data.pageNum == res.data.pages
            })
        },
        async videoPlayOrPause() {
            await this.$toLogin()
            let playingVideo = document.getElementById('video_' + this.current)
            playingVideo = playingVideo.getElementsByTagName('video')[0]
            if(playingVideo.paused) {
                this.videoContext.play()
            } else {
                this.videoContext.pause()
            }
        },
        swiperChange(e) {
            this.current = e.detail.current
            this.videoContext.pause()
            this.advertInfo = {}
            document.title = this.videoList[this.current].title
            this.wxConfig()
            if(this.current + 2 >= this.videoList.length - 1) {
                this.getVideoList()
            }
            this.$nextTick(this.initVideoContext)
        },
        initVideoContext() {
            this.videoContext = uni.createVideoContext('video_' + this.current, this)
            this.videoContext.seek(0)
            this.videoContext.play()
            this.isPause = false
        },
        videoStatus(e, status) {
            if(e.type == 'ended') {
                // this.videoContext.seek(0)
                this.videoContext.stop()
                this.isPause = true
                this.uploadReadTime()
            }
            if(e.type == 'play') {
                this.isPause = false
            }
            if(e.type == 'pause') {
                this.isPause = true
            }
            console.log(e, status);

        },
        videoTimeupdate(e) {
            console.log(e);
            this.videoTime.maxCurrentTime = e.detail.currentTime > this.videoTime.maxCurrentTime ? e.detail.currentTime : this.videoTime.maxCurrentTime

            this.videoTime.currentTime = e.detail.currentTime
            this.videoTime.duration = e.detail.duration

            this.videoTime.fomatCurrentTime =  timestampToCountdown(e.detail.currentTime * 1000, 'mm:ss') 
            this.videoTime.formatDuration = timestampToCountdown(e.detail.duration*1000, 'mm:ss')
            
            if(!!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
                this.playIngCb()
            }
        },
        playIngCb: throttle(function() {
            this.uploadReadTime()
        }, 2 * 1000),
        uploadReadTime() {
            if(!this.shareKey) return;
            if(this.$store.state.user.account.token && this.detail.hisId) {
                if(this.videoTime.currentTime < 1) return
                if(this.videoTime.currentTime < this.videoTime.maxCurrentTime ) return
                userHisLeave({ 
                    hisId: this.detail.hisId, 
                    second: Math.floor(this.videoTime.currentTime),
                    timeStr: Math.floor(this.videoTime.duration)
                }, { loadingIcon: false })
            }
        },

        changeTitle(item) {
            this.$refs.textEditer.open({
                content: item.title,
            }).then(rst => {
                item.title = rst
                document.title = rst
                this.wxConfig()
            })
        },
        deleteVideo(item, index) {
            this.$interact.modal({
                title: '提示',
                content: '是否删除视频？',
                showCancel: true
            }).then(action => {
                if(action.confirm) {
                    sysDeleArt({
                        id: item.id
                    }).then(res => {
                        this.$interact.toast(res.msg)
                        this.videoList.splice(index, 1)
                    })
                }
            })
        },
        async toPraise(item) {
            await this.$toLogin()
            // 目前点赞不能取消
            if(item.praiseFlag) return
            praiseDynamic({
                dynamicId: item.id
            }).then(res => {
                item.praiseFlag = Number(!item.praiseFlag)
                if(item.praiseFlag) {
                    item.praiseCnt += 1
                } else {
                    item.praiseCnt -= 1
                }
            })
        },
        async showMyCard() {
            await this.$toLogin()
            this.$checkVip('更换名片属于会员特权，开通后可无限次更换名片')
            this.$interact.modal({
                title: '提示',
                content: '显示我的名片？',
                showCancel: true,
            }).then(action => {
                if(action.confirm) {
                    updateUserInfo({
                        dynamicShowCard: '01'
                    }).then(res => {
                        this.$refreshUserInfo()
                    })
                }
            })
        },
        async insertAd() {
            await this.$toLogin()
            await this.$checkVip()
            this.$refs.adSelecter.open().then((rst) => {
                if(rst.isAll) {
                    this.getDefaultAd()
                }
                this.advertInfo = rst
            })
        },
        async backTop() {
            await this.$toLogin()
            await this.checkGZHstatus()
            // 被刷新后，历史记录不存在了，需要返回到首页
            let prePageFullPath = this.$prePage() && this.$prePage().__page__.fullPath || ''
            if(!prePageFullPath) {
                this.$navigate.to('/pages/material')
            }
            // 根据下一篇的数量计算返回素材库应该后退的步数
            uni.navigateBack({
                delta: 1,
                fail() {
                    if(this.detail.userId && this.detail.userId != '0') {
                        this.$navigate.to('/pages/user/myMaterial')
                    } else {
                        this.$navigate.to('/pages/material')
                    }
                }
            })
        },
        async shareCopy(item) {
            await this.$toLogin()
            this.$refs.timelineTip.open(item.title)
        },
        getShareLink() {
            let linkQueryStr = this.$qs.stringify({                    
                id: this.dynamicId,
                shareKey: this.fromUserId == this.$store.state.user.userInfo?.userId ? this.shareKey : this.tempShareKey,
                inviteUserId: this.mixinLoginStatus ? this.$store.state.user.userInfo.userId : ''
            })
            let link = location.origin +  location.pathname + '?' + linkQueryStr
            return link
        },
        wxConfig() {
            let that = this
            const setShareInfo = () => {
                let shareData = {
                    title: this.detail.title, // 分享标题
                    link: this.getShareLink(),  // 分享链接
                    imgUrl: this.detail.pictureUrl, // 分享图标
                } 
                jWeixin.onMenuShareTimeline({
                    ...shareData,
                    success: function () {
                        // 用户确认分享后执行的回调函数
                        that.shareArt('01')
                    }
                })
                jWeixin.onMenuShareAppMessage({
                    ...shareData,
                    success: function () {
                        // 用户确认分享后执行的回调函数
                        that.shareArt('00')
                    }
                })
            }
            if(this.hasAlreadyWxConfig) {
                setShareInfo()
            } else {
                this.$wxConfig().then(() => {
                    this.hasAlreadyWxConfig = true
                    setShareInfo()
                })
            }
        },
        shareArt(shareType) {
            if(!this.mixinLoginStatus) return;
            let data = {
                frontKey: this.fromUserId == this.$store.state.user.userInfo?.userId ? this.shareKey : this.tempShareKey,
                formKey: this.fromUserId == this.$store.state.user.userInfo?.userId ? '' : this.shareKey,
                dynamicId: this.detail.id,
                advertId: this.advertInfo.id || this.defaultAdverInfo.id || void 0
            }
            if(shareType == 'poster') {
                data.tempFlag = '01'
                data.shareType = '00'
            } else {
                data.shareType = shareType //00群聊，01朋友圈
            }
            shareDynamic(data).then(res => {
                if( process.env.NODE_ENV == 'development') {
                    this.$interact.modal('分享成功')
                } else {
                    this.$interact.toast('分享成功')
                }
            })
        },
        createPoster() {
            this.$refs.createPoster.create({
                type: 'video',
                title: this.detail.title,
                mainPic: this.detail.pictureUrl,
                linkQrcode: this.getShareLink() + '&isPoster=1',
            }).then(() => {
                this.shareArt('poster')
            })
        },
        async changeMyCard() {
            await this.$toLogin() 
            await this.checkGZHstatus()
            location.replace('/pages/material/video?id=' + this.dynamicId)
        },
        async saveToPhone(item) {
            console.log(item);
            await this.$toLogin() 
            await this.$checkVip()
            let url = '/pagesA/download/video?source=' + encodeURIComponent(item.context)
            let data = {
                scene: JSON.stringify({url}),
                path: 'pages/scan', //想要生成小程序码的页面地址
                width: '300', //小程序码大小
                platCode: 'jdkj',
                platform: '00',
                owxId: '475240228932550656',
                token: void 0
            };
            this.downloadCodeError = false 
            getAppCode(data).then(res => {   
                this.downloadCodeUrl = res.data.url
                this.$refs.downloadVide.open()
            })
        },
        handleDownloadCodeUrlError(e) {
            this.downloadCodeError = true 
            console.log(e);
        },
        copyErrorUrl() {
            uni.setClipboardData({
                data: this.downloadCodeUrl,
                success: () => {
                    this.$interact.toast('已复制')      
                }
            })
        },
        checkGZHstatus() {
            return new Promise((resolve, reject) => {
                if(this.$store.state.user.userInfo.subscribeFlag == '01' || this.canEdit) { //有关注过公众号或者已经进入可编辑状态
                    resolve()
                } else {
                    this.$refs.gzhPopup.open({
                        refType: '01',
                        refId: this.detail.id,
                    })
                }
            })
        }
    }

}
</script>

<style lang="less" scoped>
    .swiper{
        width: 100%;
        height: 100vh;
        background: #000;
        .video_container{
            width: 100%;
            height: 100%;
            video{
                width: 100%;
                height: 100%;
            }
        }
    }

    .video_cover{
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 5;
        .play_icon{
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: #fff;
            .align(center, column);
            .icon-video-play{
                opacity: 0.6;
                font-size: 80rpx;
            }
            span{
                opacity: 0.9;
                font-size: 30rpx;
            }
        }
        .back_material{
            background: @mainColor;
            position: absolute;
            top: 50rpx;
            left: 0;
            border-radius: 0 30rpx 30rpx 0;
        }
        .change_title{
            position: absolute;
            background: rgba(0, 0, 0, 0.6);
            top: 50rpx;
            right: 20rpx;
            border-radius: 30rpx;
        }
        .delete_video{
            position: absolute;
            background: rgba(255, 0, 0, 0.6);
            top: 140rpx;
            right: 20rpx;
            border-radius: 30rpx;
        }
        .right_icon{
            position: absolute;
            right: 30rpx;
            top: 50%;
            transform: translateY(-50%);
            // width: 80rpx;
            // background: #fff;
            .avator{
                width: 80rpx;
                height: 80rpx;
                background: #fff;
                border-radius: 50%;
                image{
                    width: 100%;
                    height: 100%;
                    border-radius: 50%;
                }
            }
            .icon_item{
                margin-bottom: 30rpx;
                i{
                    color: #fdfdfd;
                    font-size: 40rpx;
                    width: 80rpx;
                    height: 80rpx;
                    line-height: 80rpx;
                    background: rgba(0, 0, 0, 0.5);
                    border-radius: 50%;
                    .align(center);
                    &.icon-tupian{
                        font-size: 34rpx;
                    }
                }
                p{
                    font-size: 24rpx;
                    color: #fff;
                    text-align: center;
                    line-height: 40rpx;
                    text-shadow: 0 0 4rpx #000;
                }
            }
        }

        .download{
            position: absolute;
            bottom: 40rpx;
            right: 20rpx;
            .align(center, column);
            .wx-open-launch-weapp{
                width: 100rpx;
                display: block;
            }
            a{
                display: block;
                width: 100%;
                height: 100%;
                .align(center, column);
            }
            i{
                width: 80rpx;
                height: 80rpx;
                line-height: 80rpx;
                border-radius: 50%;
                color: #fff;
                font-size: 48rpx;
                .align(center);
                padding-left: 5rpx;
                .gradient(#71a0f9, #8c5dfe, to bottom);
            }
            p{
                color: #fff;
                font-size: 24rpx;
                line-height: 40rpx;
                margin-top: 10rpx;
            }
        }   


        .ad_container{
            // width: 500rpx;
            position: absolute;
            bottom: 0;
            left: 0;
            padding: 20rpx;
            .v_ad_info{
                width: 550rpx;
                min-height: 160rpx;
                border-radius: 20rpx;
                overflow: hidden;
                background: #fff;
                /deep/.ad_item{
                    margin-bottom: 0;
                    .ad_info{
                        padding: 10rpx!important;
                        image{
                            width: 150rpx;
                            height: 150rpx;
                        }
                        .ad_des{
                            height: 150rpx;
                            p{
                                height: 100rpx;
                            }
                        }
                    }
                }
            }
            .ad_btn{
                width: 550rpx;
                height: 60rpx;
                background: @mainColor;
                color: #fff;
                margin-top: 20rpx;
                border-radius: 30rpx;
                .align(center);
            }
        }
    }

    .alert_download_video{
        width: 560rpx;
        // height: 600rpx;
        background: #fff;
        border-radius: 20rpx;
        .title{
            width: 100%;
            font-size: 44rpx;
            text-align: center;
            line-height: 120rpx;
        }
        .img_con{
            width: 360rpx;
            height: 360rpx;
            margin: 20rpx auto;
            position: relative;
            image{
                width: 360rpx;
                height: 360rpx;
                display: block;
            }   
            .error{
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                .align(center, column);
                span{
                    word-break: break-all;
                    &:first-child{
                        margin-bottom: 10rpx;
                    }
                    &:last-child{
                        color: #999;
                        font-size: 24rpx;
                    }
                }

            }
        }
        p{
            text-align: center;
            font-size: 28rpx;
            color: #999;
            padding: 30rpx 0;
        }
    }
    .video_num{
        position: absolute;
        bottom: 10rpx;
        right: 10rpx;
        font-size: 20rpx;
        color: #999;

    }
</style>